"""
赛事
"""
import datetime
import json
from django.db import transaction
import logging

from src.utils import record, hxIm
from common.models import TbMiniappUser, TbLeaderboard, TbLikeRecord, TbGames, ImChatgroup

errlog = logging.getLogger("err")


class GameDirector:
    def __init__(self):
        self.gr = record.GameRecord()
        self.gpr = record.GamePicRecord()
        self.gar = record.GameApplyRecord()
        self.ima = hxIm.ImAgent()

    def publish_game(self, **kwargs):
        """
        发布赛事
        """
        user: TbMiniappUser = kwargs.get("user")
        name = kwargs.get("name")
        city = kwargs.get("city")
        address = kwargs.get("address")
        start_time = kwargs.get("start_time")
        end_time = kwargs.get("end_time")
        rule = kwargs.get("rule")
        reward = kwargs.get("reward")
        cover = kwargs.get("cover")
        game_pics = kwargs.get("game_pics")
        type = kwargs.get("type")
        apply_price = kwargs.get("apply_price")
        if apply_price is None:
            apply_price = 0
        need_pay = 0
        if eval(apply_price) > 0:
            need_pay = 1
        with transaction.atomic():
            # 创建讨论组
            chatgroup_info = {
                "groupname": f"{name}-讨论组",
                "description": f"{name}-讨论组",
                "owner": user.phone,
                "custom": {}
            }
            chatgroup: ImChatgroup = self.ima.create_course_task_chatGroup(**chatgroup_info)
            game_info = {
                "name": name,
                "city": city,
                "address": address,
                "start_time": start_time,
                "end_time": end_time,
                "rule": rule,
                "reward": reward,
                "cover": cover,
                "create_user": user.username,
                "create_user_id": user.uid,
                "type": type,
                "apply": 1000,
                "follow": 1000,
                "apply_price": apply_price,
                "need_pay": need_pay,
                "chatgroup_id": chatgroup.group_id,

            }
            game = self.gr.create_record(**game_info)
            result = self.gr.record_obj_serializer(game)
            # 给赛事添加赛事图
            if game_pics is not None:
                for game_pic in game_pics:
                    pic_info = {
                        "pic_url": game_pic.get("url"),
                        "game_id": game.uid
                    }
                    self.gpr.create_record(**pic_info)
                pic_list = self.gpr.filter_record(game_id=game.uid, is_delete=0)
                result["pic_list"] = pic_list
            return result

    def get_game_list(self, **kwargs):
        """
        获取赛事列表
        """
        user: TbMiniappUser = kwargs.get("user")
        page = kwargs.get("page")
        size = kwargs.get("size")
        type = kwargs.get("type")
        select_info = {
            "is_delete": 0
        }
        if type is not None:
            select_info["type"] = type
        return self.gr.filter_record_page(page=page, size=size, **select_info)

    def get_game_detail(self, **kwargs):
        """
        获取赛事详情
        """
        game_id = kwargs.get("game_id")
        # 赛事图
        game_pic = self.gpr.filter_record(game_id=game_id, is_delete=0)
        result = self.gr.get_record_detail(game_id)
        result["game_pic"] = game_pic
        return result

    def apply(self, **kwargs):
        """
        赛事报名
        """
        game_id = kwargs.get("game_id")
        name = kwargs.get("name")
        phone = kwargs.get("phone")
        address = kwargs.get("address")
        user: TbMiniappUser = kwargs.get("user")
        # 验证
        # --- start ---
        # 验证该赛事是否报名过
        is_exits = self.gar.exits_record(game_id=game_id, phone=phone, is_delete=0)
        if is_exits:
            raise ValueError("已经报名过了")
        # --- end ---
        with transaction.atomic():
            game: TbGames = self.gr.get_record(game_id)
            apply_info = {
                "game_id": game_id,
                "name": name,
                "phone": phone,
                "address": address,
                "need_pay": game.need_pay,
                "is_payed": 0
            }
            game_apply = self.gar.create_record(**apply_info)
            # 修改赛事报名人数
            game.apply += 1
            game.save()
            # 加入讨论组
            username = user.username
            group_id = game.chatgroup_id
            join_result = self.ima.join_chatGroup(username=username, group_id=group_id)
            errlog.info(json.dumps(join_result))
            return self.gar.record_obj_serializer(game_apply)
